package com.hc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.hc.common.BaseConfig;
import com.hc.common.SensorHub;

public class SensorHubServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String actionType = req.getParameter("actionType");  
		if("getSensorHub".equals(actionType)){
			getSensorHub(req, resp);
		}else if("addSensorHub".equals(actionType)){
			addSensorHub(req, resp);
		}else if("deleteSensorHub".equals(actionType)){
			deleteSensorHub(req, resp);
		}
	}
	
	private void addSensorHub(HttpServletRequest req, HttpServletResponse resp){
		String hostIp = req.getParameter("serverIp");
		int port = Integer.parseInt(req.getParameter("serverPort"));
		SensorHub hub = new SensorHub(hostIp, port);
		if(!BaseConfig.sensorHubList.contains(hub)){
			hub.setId(BaseConfig.sensorHubList.size());
			BaseConfig.sensorHubList.add(hub);
		}
	}
	
	private void deleteSensorHub(HttpServletRequest req, HttpServletResponse resp){
		int id = Integer.parseInt(req.getParameter("id"));
		Iterator<SensorHub> it = BaseConfig.sensorHubList.iterator();
		while(it.hasNext()){
			SensorHub hub = it.next();
			if(hub.getId() == id){
				it.remove();
			}
		}
		resetSensorhubId();
	}
	
	private void resetSensorhubId(){
		for(int i = 0; i < BaseConfig.sensorHubList.size(); i++){
			SensorHub hub = BaseConfig.sensorHubList.get(i);
			hub.setId(i);
		}
	}
	
	private void getSensorHub(HttpServletRequest req, HttpServletResponse resp){
		returnMsg(req, resp, JSONArray.toJSONString(BaseConfig.sensorHubList));
	}
	
	private void returnMsg(HttpServletRequest req, HttpServletResponse resp,
			String msg) {
		resp.setCharacterEncoding("utf-8");

		PrintWriter w;
		try {
			w = resp.getWriter();
			w.write(msg);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	
}
